package com.hds.modules.app.controller;

import com.hds.common.exception.RRException;
import com.hds.common.utils.R;
import com.hds.modules.sys.controller.AbstractController;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hds.modules.sys.entity.base.SysMemberShipEntity;
import com.hds.modules.sys.entity.base.SysMemberShipRecordsEntity;
import com.hds.modules.sys.service.base.SysMemberShipRecordsService;
import com.hds.modules.sys.service.base.SysMemberShipService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.hds.common.validator.Assert;
import com.hds.modules.app.annotation.Login;
import com.hds.modules.app.annotation.LoginUser;
import com.hds.modules.app.entity.UserEntity;
import com.hds.modules.app.entity.wx.common.CommonUtils;
import com.hds.modules.app.entity.wx.handler.UnifiedOrderApi;
import com.hds.modules.app.entity.wx.po.UnifiedOrder;
import com.hds.modules.app.entity.wx.po.UnifiedOrderResult;
import com.hds.modules.app.utils.WechatUtils;
import com.google.gson.Gson;

@RestController
@RequestMapping("/app/pay")
public class PayController extends AbstractController {

    @Autowired
    WechatUtils wechatUtils;

    @Autowired
    private SysMemberShipService sysMemberShipService;

    @Autowired
    private SysMemberShipRecordsService sysMemberShipRecordsService;

    /**public String wxPay(HttpServletRequest req, HttpServletResponse response,
                        Integer gid,
                        InsuranceOrder order,
                        UserEntity user) throws Exception{

        String txnAmt ="";
        Product product = productService.queryObject(gid);
        Assert.isNull(product, "未找到当前商品");
        BigDecimal sellPrice = product.getSellPrice();
        txnAmt = sellPrice.toString(); //支付金额

        String orderNo=""; //订单编号
        try {请求XML数据
            String json = "";
            Gson g = new Gson();
            BigDecimal finalAmount=null;

            finalAmount=new BigDecimal(txnAmt); //最终支付金额
            SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
            orderNo="vip"+sdf.format(new Date());
            UnifiedOrderResult unifiedOrderWeixin=null;
            //调用统一下单接口
            unifiedOrderWeixin = unifiedOrderWeixin(req, orderNo , user.getOpenid(),String.valueOf(finalAmount.multiply(new BigDecimal("100")).intValue()));
            unifiedOrderWeixin.setOrderAmount(txnAmt);
            unifiedOrderWeixin.setPayableAmount(finalAmount.toString());
            if (null != unifiedOrderWeixin){
                json = g.toJson(unifiedOrderWeixin);
                logger.info("获取签名后的json格式字符串:{}",json);
                return "{\"status\":\"get_data_success\",\"data\":"+json+"}";
            } else {
                json = g.toJson(new String("packageError"));
                logger.info("获取签名后的json格式字符串出错了:{}",json);
                return "{\"status\":\"get_data_error\",\"data\":"+json+"}";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
     */


    private static final String FROM_VIP = "VIP";
    private static final String FROM_GOODS = "GOODS";


    /**
     * 【微信支付】
     * @param req
     * @param response
     * @param map
     * @return
     * @throws Exception
     */
	@Login
	@RequestMapping("wechat")
    public R wechatPay(@LoginUser UserEntity user, HttpServletRequest req, HttpServletResponse response, @RequestParam Map<String, Object> map) throws Exception{

        String txnAmt ="",id="",orderNo="";
        Integer orderId=null; //订单编号
        BigDecimal realAmount=null;

        Gson g = new Gson();
        BigDecimal finalAmount=null;


        String orderIdStr = (String)map.get("orderId");
        orderId = Integer.valueOf(orderIdStr);
//        orderNo = (String)map.get("orderNo");
//        Assert.isNull(orderNo, "订单编号不能为空");


        SysMemberShipEntity memberShip = null;
        logger.info("===map:{}===", map.toString());
        // 支付来自VIP升级
        if(map!=null && map.get("from")!=null){
            String f = (String)map.get("from");
            logger.info("====支付来自VIP升级:{}====", f);
            if(f.toUpperCase().equals(FROM_VIP)){
                SysMemberShipRecordsEntity  sysMemberShipRecordsEntity = sysMemberShipRecordsService.selectById(orderId);
                orderNo = sysMemberShipRecordsEntity.getOrderNo();
                Assert.isNull(sysMemberShipRecordsEntity, "该订单不存在");
                finalAmount = new BigDecimal(sysMemberShipRecordsEntity.getRealAmount()); // 最终支付金额
            }

            // 支付来自商品

        }else{
            throw new RRException("请检查参数是否传递正常");
        }


        try {
            UnifiedOrderResult unifiedOrderWeixin=null;
            logger.info("====调用统一下单接口 入参===：openid:{}, orderNo:{}, finalAmount:{}",orderNo, user.getOpenid(), finalAmount);
            //调用统一下单接口
            unifiedOrderWeixin = unifiedOrderWeixin(req, orderNo , user.getOpenid(),String.valueOf(finalAmount.multiply(new BigDecimal("100")).intValue()));
            unifiedOrderWeixin.setOrderAmount(txnAmt);
            unifiedOrderWeixin.setPayableAmount(finalAmount.toString());
            logger.info("获取签名后的json格式字符串:{}",unifiedOrderWeixin);
            if (null != unifiedOrderWeixin){
                return R.ok().put("data", unifiedOrderWeixin);
            } else {
                return R.error().put("data", unifiedOrderWeixin);
            }
        } catch (Exception e) {
            logger.info("Exception caught..."+e.getMessage());
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 微信统一出单接口
     * @param request
     * @param orderId 订单编号
     * @param openId  用户编号
     * @param money   金额
     * @throws Exception
     */
    private UnifiedOrderResult unifiedOrderWeixin(HttpServletRequest request,
                                                  String orderId, String openId, String money) throws Exception{
        // 获取微信公众号的 appId
        // 根据 orgCode 系列获得
        UnifiedOrderResult unifiedOrderResult = null;
        DecimalFormat dfAmount = new DecimalFormat("#");
        //创建订单参数对象
        UnifiedOrder unifiedOrder = new UnifiedOrder();
        //设置订单参数
        unifiedOrder.setAppid(wechatUtils.getAppId());
        unifiedOrder.setOpenid(openId);
        unifiedOrder.setBody("订单支付...");
        unifiedOrder.setOut_trade_no(orderId); //订单号
        unifiedOrder.setTotal_fee(money); // 总费用（单位：分）
        unifiedOrder.setSpbill_create_ip(CommonUtils.getIpAddr(request));
        unifiedOrder.setAttach("");
        logger.info("传人的总金额："+unifiedOrder.getTotal_fee());
        logger.info("IP地址:"+unifiedOrder.getSpbill_create_ip());

        //防止 time_expire时间过短，刷卡至少1分钟，其他5分钟
        //时间格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        Date now = new Date();
        Date afterDate = new Date( now.getTime() + 300000);
        //设置交易起始时间
        unifiedOrder.setTime_start(sdf.format(now));
        //设置交易结束时间
        unifiedOrder.setTime_expire(sdf.format(afterDate));
        //开始真正调用微信支付的统一下单接口
        unifiedOrderResult = UnifiedOrderApi.unifiedOrderK(unifiedOrder, request);
        // 将prepayId要保存到数据库中，以便一天之内再次发起请求时不用再次进行下单操作，一天之后订单无法支付
        return unifiedOrderResult;
    }

}
